define([
    "dojo/_base/declare",
    "dijit/_Widget",
    "dijit/_Templated",
    "dojo/text!./ProductForm/template/form.html",
    "dojo/_base/kernel",
    "widget/RankingChart",
    "dojo/behavior",
    "dijit/form/TextBox",
    "dijit/form/Select",
    "dijit/form/Button",
    "dijit/form/MultiSelect",
    "dijit/form/Form",
    "dijit/Editor",
    "dijit/form/SimpleTextarea"],
    function(declare, _Widget,_Templated,templateHtml,dojo,RankingChart,Behavior){
        return declare("widget.ProductForm",[_Widget,_Templated], {
            widgetsInTemplate: true,
            baseClass: "product-form",
            templateString: templateHtml,
            readOnly: false,
            
            postCreate: function(){
                this.inherited(arguments);
                this.bindAction();
                this.rankingChart.initChart();
                this.loadProductTypes();
                Behavior.apply();
            },
            
            loadProduct:function(id){
                var xhrArgs = {
                    url:"product/getproduct/pid/"+id,
                    handleAs: "json"
                };
                var deferred = dojo.xhrPost(xhrArgs);
                deferred.then(dojo.hitch(this,function(result){
                    dijit.byId("productForm1").set("value",result);
                    this.updatedTime.innerHTML = result.UpdateTime;
                    this.createdTime.innerHTML = result.CreateTime;
                    this.photo.src = djConfig.image + result.Photo;
                    
                    var supplies = result.supplies;
                    if (supplies){
                        for (var i=0;i<supplies.length;i++){
                            this.loadProductSupply(supplies[i].SupplyTypeID,supplies[i].SupplyID);
                        }
                    }
                    
                    this.loadRanking();
                }));
            },
            
            loadProductTypes:function(){
                var productTypes = this.productTypeSelect;
                var xhrArgs = {
                    url:"product/getproducttype",
                    handleAs: "json"
                };
                var deferred = dojo.xhrPost(xhrArgs);
                deferred.then(function(result){
                    var options = [];
                    for(var i in result){
                        options.push({value:result[i].ID,label:result[i].TypeProduct});
                    }
                    productTypes.addOption(options);
                });
            },
            
            save:function(){
                var xhrArgs = {
                    url: "product/save",
                    form: "productForm1",
                    handleAs: "json",
                    content:{
                        "MainFabrics":this.mainFabricsEditor.get("value"),
                        "PackingDetail":this.packingDetailEditor.get("value"),
                        "ProductDescription":this.productDescriptionEditor.get("value"),
                        "Like":this.likeEditor.get("value")
                    }
                };
                var deferred = dojo.xhrPost(xhrArgs);
                deferred.then(dojo.hitch(this,function(result){
                    this.reset();
                    this.loadProduct(result.id);
                    alert(result.message);
                }),function(error){
                    alert(error);
                });
            },
            
            bindAction: function(){
                dojo.connect(this.backButton,"onClick",dojo.hitch(this,function(){
                    dojo.style(this.domNode, "display", "none");
                    dojo.publish("ProductList/Show");
                }));
                
                dojo.connect(this.saveButton,"onClick",dojo.hitch(this,this.save));
                
                dojo.connect(this.uploadButton,"onClick",dojo.hitch(this,function(){
                    dijit.byId("productForm2").reset();
                    var id = this.productId.get("value");
                    if (!id){
                        alert("Please save first.");
                        return;
                    }
                    this.uploadProductId.set("value",id);
                    this.uploadDialog.show();
                }));
                
                dojo.connect(this.doUploadButton,"onClick",dojo.hitch(this,function(){
                    dojo.io.iframe.send({
                        form: "productForm2",
                        handleAs: "text",
                        load: dojo.hitch(this,function(response, ioArgs){
                            this.photo.src = djConfig.image + response;
                            this.uploadDialog.hide();
                        }),
                        error: function(response, ioArgs){
                            alert("error:"+response);
                        }
                    });
                }));
                
                dojo.subscribe("ProductForm/Show", null,dojo.hitch(this,function(object){
                    if (object.mode == "view"){
                        this.view(object.id);
                    }else if (object.mode == "edit"){
                        this.edit(object.id);
                    }else if (object.mode == "new"){
                        this.newProduct();
                    }
                    dojo.style(this.domNode, "display", "block");
                }));
                
                var that = this;
                Behavior.add({
                    ".product-form .add-supply" : {
                        onclick: function(){
                            var id = that.productId.get("value");
                            if (!id){
                                alert("Please save first!");
                                return;
                            }
                            var xhrArgs = {
                                url:"supply/getsupplylist/type/" + dojo.getAttr(this,"supplyType"),
                                handleAs: "json"
                            };
                            var deferred = dojo.xhrPost(xhrArgs);
                            deferred.then(dojo.hitch(this,function(result){
                                var length = that.dSupplyId.getOptions().length;
                                for (var i=0;i<length;i++){
                                    that.dSupplyId.removeOption(0);
                                }
                                var options = [];
                                for(var i in result){
                                    options.push({value:result[i].ID,label:(result[i].Ref  +" - "+ result[i].Name + " - " +" <img src='"+ djConfig.image + result[i].Photo+"' width='50px' height='50px' /> ")});
                                }
                                that.dSupplyId.addOption(options);
                                var supplyType = dojo.getAttr(this,"supplyType");
                                that.dSupplyTypeId.set("value",supplyType);
                                that.dProductId.set("value",id);
                                that.supplyDialog.show();
                            }));
                        }
                    },
                    
                    ".product-form .del-supply" : {
                        onclick: function(){
                            var id = that.productId.get("value");
                            if (!id){
                                alert("Please save first!");
                                return;
                            }
                            var supplyType = dojo.getAttr(this,"supplyType");
                            var productId = that.productId.get("value");
                            var xhrArgs = {
                                url:"product/deleteproductsupply/productId/"+productId+"/supplyTypeId/" + supplyType,
                                handleAs: "json"
                            };
                            var deferred = dojo.xhrPost(xhrArgs);
                            deferred.then(dojo.hitch(this,function(result){
                                that.loadProductSupply(supplyType);
                            }));
                            
                        }
                    },
                    
                    ".product-form .view-supply" : {
                        onclick: function(){
                            var supplytype = dojo.getAttr(this,"supplyType");
                            var supplyIdBox = dojo.query("#supplies_section .section-" + supplytype + "-1 .supply-id-field");
                            if (supplyIdBox && supplyIdBox.length>0){
                                var form = dijit.byId("supplyInfo");
                                var id = supplyIdBox[0].innerHTML;
                                form.reset();
                                
                                var supplyTypes = that.supplyTypeSelect;
                                var xhrArgs = {
                                    url:"supply/getsupplytype",
                                    handleAs: "json"
                                };
                                var deferred = dojo.xhrPost(xhrArgs);
                                deferred.then(function(result){
                                    var options = [];
                                    for(var i in result){
                                        options.push({value:result[i].ID,label:result[i].Name});
                                    }
                                    supplyTypes.addOption(options);
                                }).then(function(){
                                    var xhrArgs = {
                                    url:"supply/getsupply/sid/"+id,
                                    handleAs: "json"
                                    };
                                    var deferred = dojo.xhrPost(xhrArgs);
                                    deferred.then(dojo.hitch(this,function(result){
                                        form.set("value",result[0]);
    //                                    this.photo.src = djConfig.image + result[0].Photo;
                                    }));
                                    that.supplyInfoDialog.show();
                                });
                            }
                            
                        }
                    }
                });
                
                dojo.connect(this.supplyAddButton,"onClick",function(){
                    var xhrArgs = {
                        url: "product/saveproductsupply",
                        form: "productForm3",
                        handleAs: "json"
                    };
                    var deferred = dojo.xhrPost(xhrArgs);
                    deferred.then(dojo.hitch(this,function(result){
                        that.supplyDialog.hide();
                        that.loadProductSupply(that.dSupplyTypeId.get("value"),that.dSupplyId.get("value"));
                    },function(error){
                        alert(error);
                    }));
                });
                
                dojo.connect(this.expandButton,"onclick",dojo.hitch(this,function(){
                    dojo.query("#supplies_section .section-factor").style("display","block");
                    dojo.style(this.collapseButton,"display","inline");
                    dojo.style(this.expandButton,"display","none");
                }));
                dojo.connect(this.collapseButton,"onclick",dojo.hitch(this,function(){
                    dojo.query("#supplies_section .section-factor").style("display","none");
                    dojo.style(this.collapseButton,"display","none");
                    dojo.style(this.expandButton,"display","inline");
                }));
                
                
            },
            
            loadRanking:function(){
                var product = this.productId;
                if (product.get("value")){
                    var xhrArgs = {
                        url:"rank/getrank/pid/" + product.get("value"),
                        handleAs: "json"
                    };
                    var deferred = dojo.xhrPost(xhrArgs);
                    deferred.then(dojo.hitch(this,function(result){
                        this.rankingChart.input1.set("value",result.PRICE);
                        this.rankingChart.input2.set("value",result.WEIGHT);
                        this.rankingChart.input3.set("value",result.PRACTICAL);
                        this.rankingChart.input4.set("value",result.DURABILITY);
                        this.rankingChart.input5.set("value",result.ERGONOMICS);
                        this.rankingChart.render();
                    }),function(error){
                        alert("Load ranking error!");
                    });
                }
            },
            
            loadProductSupply:function(supplyTypeId,supplyId){
                var xhrArgs = {
                    url:"supply/getsupplytypefactor/supplytypeid/"+supplyTypeId+"/supplyid/"+supplyId,
                    handleAs: "json"
                };
                var deferred = dojo.xhrPost(xhrArgs);
                deferred.then(dojo.hitch(this,function(result){
                    var section1 =  dojo.query(".row .section-"+supplyTypeId+"-1")[0];
                    var section2 =  dojo.query(".row .section-"+supplyTypeId+"-2")[0];
                    var ref = result.Ref?result.Ref:"N/A";
                    var name = result.Name?result.Name:"N/A";
                    var img = result.Photo?("<img src='"+ djConfig.image + result.Photo + "' width='50px' height='50px'>"):"N/A";
                    section1.innerHTML = supplyId?("<span class='supply-id-field'>"+supplyId+"</span><span>"+ref +" - "+ name +" - "+ "</span>" +img):"";
                    
                    var section2HTML = "";
                    var factors = result.factors;
                    for (var i=0;i<factors.length;i++){
                        section2HTML += "<div style='margin:5px 0 5px 25px' >- " + factors[i].Subcat+": "+factors[i].RankingGrade+"</div>";
                    }
                    
                    section2.innerHTML = supplyId?section2HTML:"";
                    
                    var comment = dijit.byId("comments_type_" + supplyTypeId);
                    if (comment){
                        comment.set("value",result.Comments);
                    }
                }));
            },
            
            view: function(id){
                this.readOnly = true;
                this.setMode();
                this.reset();
                this.loadProduct(id);
            },
            
            edit:function(id){
                this.readOnly = false;
                this.setMode();
                this.reset();
                this.loadProduct(id);
            },
            
            newProduct :function(){
                this.readOnly = false;
                this.setMode();
                this.reset();
            },
            
            setMode:function(){
                var form1 = dijit.byId("productForm1");
                var form1Inputs = form1.getChildren();
                for (var i =0;i<form1Inputs.length;i++){
                    form1Inputs[i].set("disabled",this.readOnly);
                }

                this.saveButton.set("disabled",this.readOnly);
                this.uploadButton.set("disabled",this.readOnly);
                
                                
                if (this.readOnly){
                    dojo.query(".add-supply").addClass("hidden");
                    dojo.query(".del-supply").addClass("hidden");
                }else{
                    dojo.query(".add-supply").removeClass("hidden");
                    dojo.query(".del-supply").removeClass("hidden");
                } 
            },
            
            reset:function(){
                var form1 = dijit.byId("productForm1");
                var form1Inputs = form1.getChildren();
                for (var i =0;i<form1Inputs.length;i++){
                    form1Inputs[i].set("value","");
                }
                this.photo.src = '';
                this.createdTime.innerHTML = "";
                this.updatedTime.innerHTML = "";
                
                for(var i=1;i<=23;i++){
                    var section1 =  dojo.query(".row .section-"+i+"-1")[0];
                    var section2 =  dojo.query(".row .section-"+i+"-2")[0];
                    section1.innerHTML="";
                    section2.innerHTML="";
                }
                dojo.query("#supplies_section .section-factor").style("display","none");
                dojo.style(this.collapseButton,"display","none");
                dojo.style(this.expandButton,"display","inline");
                
                this.rankingChart.input1.set("value",0);
                this.rankingChart.input2.set("value",0);
                this.rankingChart.input3.set("value",0);
                this.rankingChart.input4.set("value",0);
                this.rankingChart.input5.set("value",0);
                this.rankingChart.render();
            }
            
        });
    });